package main;

import main.Link.LinkArray;
import main.Link.SQLLink;
import main.SQL.MsSQLConnect;
import main.Trees.ProjectNode;
import main.Trees.SmetNode;
import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.JXTreeTable;
import org.jdesktop.swingx.decorator.ColorHighlighter;
import org.jdesktop.swingx.decorator.PatternPredicate;
import org.omg.CORBA.INTERNAL;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.Book;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by s_shmakov on 01.04.14.
 */
public class SKForm extends JFrame{

    private JXTreeTable taskSmetLinkTree;
    private JTextField dateStart, dateFinish;
    private JTable taskSmetLinkTable;
    private JScrollPane jScrollPane;
    private DefaultTableModel taskSmetLinkModel;
    private JPanel panel;
    private JButton filterStart;
    private JLabel labelDateStart, labelDateFinish, labelHideWorks;
    private ProjectNode curProject;
    public SmetNode myNode, temp;
    private JToggleButton hideWorks, filterSelected;
    private KSTreeModel ksTreeModel;
    private SKTreeModel skTreeModel;
    public LinkArray linkArray;
    private ArrayList<Object[]> tableLink;
    private Connection connsql;
    private HashMap<Integer, String> smrUnit = new HashMap<>();
    private GridBagConstraints c;
    private JScrollPane scrollForTable;
    private JXDatePicker pickerStart, pickerFinish;
    //Форма выбора комплекса(сметы)
    private JFrame frame;
    private JScrollPane scrollPane;
    private JList smetList;
    private DefaultListModel listModel;
    private JButton Ok, notOk;
    //Загрузка комплексов(сметы)
    private HashMap<Integer, SmetNode> smcHash;
    private ArrayList<SmetNode> smc, smt, smo, sms;
    private Statement stat;
    private HashMap<String, SmetNode> list;
    private HashMap<Integer, ProjectNode> taski;

    public SKForm(ProjectNode curProject, LinkArray linkArray) {
        this.curProject = curProject;
        this.linkArray = linkArray;
        this.tableLink = new ArrayList<Object[]>();
    }

    public void chooseSmet() {

        frame = new JFrame();
        frame.setLayout(new GridBagLayout());
        GridBagConstraints c;
        int width = 300;
        int height = 400;
        frame.setSize(new Dimension(width, height));
        Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation(screensize.width / 2 - width / 2, screensize.height / 2 - height / 2);
        frame.setTitle("Отчет по привязанным сметам");

        JLabel sayUser = new JLabel("Выберите комплекс: ");
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.insets = new Insets(10, 10, 10, 10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.anchor = GridBagConstraints.EAST;
        frame.add(sayUser, c);

        listModel = new DefaultListModel();
        smetList = new JList(listModel);
        scrollPane = new JScrollPane(smetList);
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 2;
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1;
        c.weighty = 1;
        c.insets = new Insets(10, 10, 10, 10);
        frame.add(scrollPane, c);

        Ok = new JButton("Сформировать 2СК");
        Ok.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                SKSQLSmet skSQLSmet = new SKSQLSmet();
                temp = skSQLSmet.open(list.get(listModel.getElementAt(smetList.getSelectedIndex())).getId());
                for (SmetNode sm : temp.getChildren()) {
                    if (sm.getId() == list.get(listModel.getElementAt(smetList.getSelectedIndex())).getId()) {
                        myNode = sm;
                        setTask();
                        addSmet(myNode, linkArray);
                    }
                }
                openSKForm();
                frame.setVisible(false);
            }
        });
        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 2;
        c.insets = new Insets(10, 10, 10, 10);
        frame.add(Ok, c);

        notOk = new JButton("Отмена");
        notOk.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                frame.setVisible(false);
            }
        });
        c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 2;
        c.anchor = GridBagConstraints.WEST;
        c.insets = new Insets(10, 10, 10, 10);
        frame.add(notOk, c);

        setComplex();
        frame.setVisible(true);
    }

    private void setComplex() {
        connsql = MsSQLConnect.ConnectDB("TST");
        list = new HashMap<String, SmetNode>();
//        arrList = new ArrayList<SmetNode>();
        smc = new ArrayList<SmetNode>();
        smt = new ArrayList<SmetNode>();
        smo = new ArrayList<SmetNode>();
        sms = new ArrayList<SmetNode>();
        try {
            //загрузка списка для List
            stat = connsql.createStatement();
            ResultSet rs = stat.executeQuery("SELECT complex_id, name FROM ks_Complex");
            while ( rs.next() ){
                this.list.put(rs.getString("name"), new SmetNode(0, rs.getInt("complex_id"), rs.getString("name")));
                this.smc.add( new SmetNode(0, rs.getInt("complex_id"), rs.getString("name")));
            }

            rs.close();
            stat.close();
            connsql.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        for (SmetNode smr : smc) {
            listModel.addElement(smr.getName());
        }
    }

    public void openSKForm() {

        setTitle("Форма КС-2");
        panel = new JPanel();
        add(panel);
        int width = 1000;
        int height = 750;
        setSize(new Dimension(width, height));
        Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation(screensize.width / 2 - width / 2, screensize.height / 2 - height / 2);

        taskSmetLinkTable = new JTable(taskSmetLinkModel);

        scrollForTable = new JScrollPane(taskSmetLinkTable);
        scrollForTable.setVisible(false);

        labelDateStart = new JLabel("Начало");
        labelDateFinish = new JLabel("Конец");

        pickerStart = new JXDatePicker();
        pickerFinish = new JXDatePicker();

        dateStart = new JTextField(15);
        dateStart.setMinimumSize(new Dimension(90,20));
        dateFinish = new JTextField(15);
        dateFinish.setMinimumSize(new Dimension(90,20));

        filterStart = new JButton("Фильтр");
        filterStart.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                reInit();
            }
        });

        skTreeModel = new SKTreeModel();
        System.out.println(myNode.getChildCount());
        skTreeModel.openSmet(myNode);

        taskSmetLinkTree = new JXTreeTable(skTreeModel);
        taskSmetLinkTree.setSize(new Dimension(900,650));
        formatTaskSmetLinkTree();
        taskSmetLinkTree.updateUI();

        panel.setLayout(new GridBagLayout());

        hideWorks = new JToggleButton("Форма КС-2");
        hideWorks.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {

            }
        });

        filterSelected = new JToggleButton("Форма КС-2 по выбранному");
        filterSelected.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {

            }
        });

        jScrollPane = new JScrollPane(taskSmetLinkTree);
        jScrollPane.setPreferredSize(new Dimension(900, 650));

        c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 6;
        c.weightx = 1;
        c.weighty = 1;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(25, 25, 5, 25);
        c.anchor = GridBagConstraints.WEST;
        panel.add(jScrollPane, c);

        setVisible(true);

    }

    private void reInit() {

    }

    private void formatTaskSmetLinkTree() {

        try {
            Image iconTask = ImageIO.read(getClass().getResource("images/leaf.png"));
            taskSmetLinkTree.setLeafIcon(new ImageIcon(iconTask));
            Image iconWbs = ImageIO.read(getClass().getResource("images/wbs.png"));
            taskSmetLinkTree.setOpenIcon(new ImageIcon(iconWbs));
            taskSmetLinkTree.setClosedIcon(new ImageIcon(iconWbs));

        } catch (IOException e) {
            e.printStackTrace();
        }


        PatternPredicate leafPr = new PatternPredicate(".", 3);
        ColorHighlighter leafs = new ColorHighlighter(leafPr, Color.white, null, null, null);
        PatternPredicate rootPr = new PatternPredicate("ROOT", 1);
        ColorHighlighter rootHL = new ColorHighlighter(rootPr, new Color (100,149,237), Color.white, null, null);
        PatternPredicate wbsPr0 = new PatternPredicate("WBS0", 1);
        ColorHighlighter wbsHL0 = new ColorHighlighter(wbsPr0, new Color (122,155,218), Color.white, null, null);
        PatternPredicate wbsPr1 = new PatternPredicate("WBS1", 1);
        ColorHighlighter wbsHL1 = new ColorHighlighter(wbsPr1, new Color (144,162,200), Color.white, null, null);
        PatternPredicate wbsPr2 = new PatternPredicate("WBS2", 1);
        ColorHighlighter wbsHL2 = new ColorHighlighter(wbsPr2, new Color (167,168,181), Color.black, null, null);
        PatternPredicate wbsPr3 = new PatternPredicate("WBS3", 1);
        ColorHighlighter wbsHL3 = new ColorHighlighter(wbsPr3, new Color (189,174,163), Color.black, null, null);
        PatternPredicate wbsPr4 = new PatternPredicate("WBS4", 1);
        ColorHighlighter wbsHL4 = new ColorHighlighter(wbsPr4, new Color (211,181,144), Color.black, null, null);

        taskSmetLinkTree.setHighlighters(leafs, wbsHL0, wbsHL1, wbsHL2, wbsHL3, wbsHL4, rootHL );

        taskSmetLinkTree.setRowHeight(20);
        taskSmetLinkTree.setGridColor( new Color (219, 219, 219) );
        taskSmetLinkTree.setShowGrid( true, true);

        if (taskSmetLinkTree.getColumnModel().getColumnCount() > 0) {
            taskSmetLinkTree.getColumnModel().getColumn(0).setMinWidth(90);
            taskSmetLinkTree.getColumnModel().getColumn(0).setPreferredWidth(150);
            taskSmetLinkTree.getColumnModel().getColumn(0).setMaxWidth(260);
            taskSmetLinkTree.getColumnModel().getColumn(2).setMinWidth(60);
            taskSmetLinkTree.getColumnModel().getColumn(2).setPreferredWidth(100);
            taskSmetLinkTree.getColumnModel().getColumn(2).setMaxWidth(120);
            taskSmetLinkTree.getColumnModel().getColumn(3).setMinWidth(60);
            taskSmetLinkTree.getColumnModel().getColumn(3).setPreferredWidth(100);
            taskSmetLinkTree.getColumnModel().getColumn(3).setMaxWidth(120);
        }
        taskSmetLinkTree.expandAll();
    }

    private void formatTaskSmetLinkTable() {

        taskSmetLinkTable.setRowHeight(20);
        taskSmetLinkTable.setGridColor( new Color (219, 219, 219) );

        if (taskSmetLinkTable.getColumnModel().getColumnCount() > 0)
        {
            taskSmetLinkTable.getColumnModel().getColumn(0).setMinWidth(20);
            taskSmetLinkTable.getColumnModel().getColumn(0).setPreferredWidth(40);
            taskSmetLinkTable.getColumnModel().getColumn(0).setMaxWidth(60);
            taskSmetLinkTable.getColumnModel().getColumn(1).setMinWidth(20);
            taskSmetLinkTable.getColumnModel().getColumn(1).setPreferredWidth(40);
            taskSmetLinkTable.getColumnModel().getColumn(1).setMaxWidth(60);
            taskSmetLinkTable.getColumnModel().getColumn(3).setMinWidth(40);
            taskSmetLinkTable.getColumnModel().getColumn(3).setPreferredWidth(100);
            taskSmetLinkTable.getColumnModel().getColumn(3).setMaxWidth(140);
            taskSmetLinkTable.getColumnModel().getColumn(4).setMinWidth(20);
            taskSmetLinkTable.getColumnModel().getColumn(4).setPreferredWidth(70);
            taskSmetLinkTable.getColumnModel().getColumn(4).setMaxWidth(120);
            taskSmetLinkTable.getColumnModel().getColumn(5).setMinWidth(20);
            taskSmetLinkTable.getColumnModel().getColumn(5).setPreferredWidth(100);
            taskSmetLinkTable.getColumnModel().getColumn(5).setMaxWidth(120);
            taskSmetLinkTable.getColumnModel().getColumn(6).setMinWidth(20);
            taskSmetLinkTable.getColumnModel().getColumn(6).setPreferredWidth(100);
            taskSmetLinkTable.getColumnModel().getColumn(6).setMaxWidth(120);

        }

    }

    private void setTask() {
        taski = new HashMap<Integer, ProjectNode>();
        connsql = MsSQLConnect.ConnectDB("Factage");
        CallableStatement stmt = null;
        try {
            stmt = connsql.prepareCall( "{call getTaskForLink()}");
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                taski.put(rs.getInt(1), new ProjectNode(rs.getString(3), rs.getString(2), rs.getInt(6), 1, true, null, null, rs.getDate(4), rs.getDate(5)));
            }
            rs.close();
            stmt.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    private void addSmet(SmetNode node, LinkArray linkArray) {

        HashMap<String, Boolean> list;
        if (node.getChildCount() > 0) {
            for (SmetNode sm : node.getChildren()) {
                sm.setAllowChildren(true);
                if (sm.getChildCount() > 0) {
                    for (SmetNode nod : sm.getChildren()) {
                        addSmet(nod, linkArray);
                    }
                } else {
                    list = new HashMap<>();
                    for (SQLLink curLink : linkArray.getLinkArray()) {
                        ProjectNode taska = taski.get(curLink.getId());
                        if (taska != null) {
                            if (sm.getId() == taska.getId()) {
                                if (list.get(curLink.getTaskShortName()) == null) {
                                    if (taska.getStartDate() == null || taska.getFinishDate() == null) {
                                        sm.add(new SmetNode(curLink.getTaskShortName(), 1, taska.getName(), "", 0.00, 0.00, 0.00, 0.00, true, 0, ""));
                                    } else {
                                        sm.add(new SmetNode(curLink.getTaskShortName(), 1, taska.getName(), taska.getStartDate().toString(), 0.00, 0.00, 0.00, 0.00, true, 0, taska.getFinishDate().toString()));
                                    }
                                    list.put(curLink.getTaskShortName(), true);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}
